﻿using IServices;
using KopSoftWms.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using YL.Core.Dto;
using YL.Core.Entity;
using YL.Core.Entity.Fluent.Validation;
using YL.NetCore.Attributes;
using YL.NetCore.NetCoreApp;
using YL.Utils.Extensions;
using YL.Utils.Pub;
using YL.Utils.Files;
using YL.Utils.Security;
using Microsoft.AspNetCore.NodeServices;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Hosting.Internal;
using Microsoft.AspNetCore.Hosting;
using YL.Utils.Delegate;
using YL.Utils.Excel;

namespace KopSoftWms.Controllers
{
    public class StockInController : BaseController
    {
        private readonly IWms_stockinServices _stockinServices;
        private readonly IWms_supplierServices _supplierServices;
        private readonly IWms_materialServices _materialServices;
        private readonly SqlSugarClient _client;
        private readonly IHostingEnvironment _hostingEnvironment;

        public StockInController(
            IWms_supplierServices supplierServices,
            IWms_stockinServices stockinServices,
            IWms_materialServices maertialServices,
            SqlSugarClient client,
            IHostingEnvironment hostingEnvironment
            )
        {
            _supplierServices = supplierServices;
            _stockinServices = stockinServices;
            _client = client;
            this._materialServices = maertialServices;
            this._hostingEnvironment = hostingEnvironment;
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult Index()
        {
            var supplierList = this._supplierServices.Queryable().Where(c => c.IsDel == 1).Select(x => new KvDict<string, string>()
            {
                Key = x.SupplierId.ToString(),
                Value = x.SupplierName
            }).ToList();

            var materialList = this._materialServices.Queryable().Where(c => c.IsDel == 1).Select(x => new KvDict<string, string>()
            {
                Key = x.MaterialId.ToString(),
                Value = x.MaterialName
            }).ToList();


            ViewData["mlist"] = materialList;
            ViewData["slist"] = supplierList;

            return View();
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult NewStockIn(string dateMin, string dateMax)
        {

            if (string.IsNullOrEmpty(dateMax))
            {
                dateMax = DateTime.Now.ToString("yyyy-MM-dd");
            }
            
            if (string.IsNullOrEmpty(dateMin))
            {
                dateMin = dateMax;
            }

            var stockInfo = this._stockinServices.GetTableStockIn(dateMin, dateMax, 0);


            ViewData["Title"] = stockInfo.Title;
            ViewData["Data"] = stockInfo.DataList;
            ViewData["TitleBm"] = stockInfo.TitleBm;
            ViewData["dateMin"] = dateMin;
            ViewData["dateMax"] = dateMax;

            return View();
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult NewStockOut(string dateMin, string dateMax)
        {

            if (string.IsNullOrEmpty(dateMax))
            {
                dateMax = DateTime.Now.ToString("yyyy-MM-dd");
            }

            if (string.IsNullOrEmpty(dateMin))
            {
                dateMin = dateMax;
            }

            var stockInfo = this._stockinServices.GetTableStockIn(dateMin, dateMax, 1);


            ViewData["Title"] = stockInfo.Title;
            ViewData["Data"] = stockInfo.DataList;
            ViewData["TitleBm"] = stockInfo.TitleBm;
            ViewData["dateMin"] = dateMin;
            ViewData["dateMax"] = dateMax;

            return View();
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult TjStockIn(string dateMin, string dateMax)
        {

            if (string.IsNullOrEmpty(dateMax))
            {
                dateMax = DateTime.Now.ToString("yyyy-MM-dd");
            }

            if (string.IsNullOrEmpty(dateMin))
            {
                dateMin = dateMax;
            }

            var stockInfo = this._stockinServices.GetTableStockIn(dateMin, dateMax, 0);


            ViewData["Title"] = stockInfo.Title;
            ViewData["Data"] = stockInfo.DataList;
            ViewData["TitleBm"] = stockInfo.TitleBm;
            ViewData["dateMin"] = dateMin;
            ViewData["dateMax"] = dateMax;

            return View();
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult TjStockOut(string dateMin, string dateMax)
        {

            if (string.IsNullOrEmpty(dateMax))
            {
                dateMax = DateTime.Now.ToString("yyyy-MM-dd");
            }

            if (string.IsNullOrEmpty(dateMin))
            {
                dateMin = dateMax;
            }

            var stockInfo = this._stockinServices.GetTableStockIn(dateMin, dateMax, 1);


            ViewData["Title"] = stockInfo.Title;
            ViewData["Data"] = stockInfo.DataList;
            ViewData["TitleBm"] = stockInfo.TitleBm;
            ViewData["dateMin"] = dateMin;
            ViewData["dateMax"] = dateMax;

            return View();
        }

        [HttpGet]
        [CheckMenu]
        public IActionResult StockOutIndex()
        {
            var supplierList = this._supplierServices.Queryable().Where(c => c.IsDel == 1).Select(x => new KvDict<string, string>()
            {
                Key = x.SupplierId.ToString(),
                Value = x.SupplierName
            }).ToList();

            var materialList = this._materialServices.Queryable().Where(c => c.IsDel == 1).Select(x => new KvDict<string, string>()
            {
                Key = x.MaterialId.ToString(),
                Value = x.MaterialName
            }).ToList();


            ViewData["mlist"] = materialList;
            ViewData["slist"] = supplierList;

            return View();
        }

        /// <summary>
        /// 主表
        /// </summary>
        /// <param name="bootstrap">参数</param>
        /// <returns></returns>
        [HttpPost]
        [OperationLog(LogType.select)]
        public ContentResult List([FromForm]PubParams.StockInBootstrapParams bootstrap)
        {
            var sd = _stockinServices.PageList(bootstrap);
            return Content(sd);
        }


        [HttpGet]
        public IActionResult Add(string id)
        {
            var model = new Wms_stockin();
            if (id.IsEmpty())
            {
                return View(model);
            }
            else
            {
                model = _stockinServices.QueryableToEntity(c => c.StockInId == SqlFunc.ToInt64(id) && c.IsDel == 1);
                return View(model);
            }
        }

        [HttpGet]
        public IActionResult StockOutAdd(string id)
        {
            var model = new Wms_stockin();
            if (id.IsEmpty())
            {
                return View(model);
            }
            else
            {
                model = _stockinServices.QueryableToEntity(c => c.StockInId == SqlFunc.ToInt64(id) && c.IsDel == 1);
                return View(model);
            }
        }

        [HttpPost]
        [FilterXss]
        [OperationLog(LogType.addOrUpdate)]
        public IActionResult AddOrUpdate([FromForm]Wms_stockin model, [FromForm]string id)
        {
            var validator = new StockInFluent();
            var results = validator.Validate(model);
            var success = results.IsValid;
            if (!success)
            {
                string msg = results.Errors.Aggregate("", (current, item) => (current + item.ErrorMessage + "</br>"));
                return BootJsonH((PubEnum.Failed.ToInt32(), msg));
            }



            if (id.IsEmptyZero())
            {
                model.StockInId = PubId.SnowflakeId;
                model.CreateBy = UserDtoCache.UserId;
                if (!string.IsNullOrEmpty(model.Unit))
                {
                    model.CreateDate = DateTime.Parse($"{model.Unit} 12:00:00");
                }
                bool flag = _stockinServices.Insert(model);
                return BootJsonH(flag ? (flag, PubConst.Add1) : (flag, PubConst.Add2));
            }
            else
            {
                model.StockInId = id.ToInt64();
                model.ModifiedBy = UserDtoCache.UserId;
                model.ModifiedDate = DateTimeExt.DateTime;
                var flag = _stockinServices.Update(model);
                return BootJsonH(flag ? (flag, PubConst.Update1) : (flag, PubConst.Update2));
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id">主表id</param>
        /// <returns></returns>
        [HttpGet]
        [OperationLog(LogType.delete)]
        public IActionResult Delete(string id)
        {
            var flag = _client.Ado.UseTran(() =>
            {
                _client.Updateable(new Wms_stockin { StockInId = SqlFunc.ToInt64(id), IsDel = 0, ModifiedBy = UserDtoCache.UserId, ModifiedDate = DateTimeExt.DateTime })
               .UpdateColumns(c => new { c.IsDel, c.ModifiedBy, c.ModifiedDate })
               .ExecuteCommand();
            }).IsSuccess;
            return BootJsonH(flag ? (flag, PubConst.Delete1) : (flag, PubConst.Delete2));
        }

        [HttpGet]
        public IActionResult PreviewJson(string id)
        {
            var str = _stockinServices.PrintList(id);
            return Content(str);
        }

        [HttpGet]
        public IActionResult WriteUploadDate (string uploadDate,string stockType)
        {
            var userId=UserDtoCache.UserId;
            var str = _stockinServices.WriteUploadInfo(uploadDate, int.Parse(stockType), userId);
            return Content(str);
        }


        [HttpGet]
        public IActionResult Export(string dateMin, string dateMax, int stockType)
        {
            var buffer = this._stockinServices.ExportList(dateMin, dateMax, stockType);
            if (buffer.IsNull())
            {
                return File(JsonL((false, PubConst.File8)).ToBytes(), ContentType.ContentTypeJson);
            }
            String fileName = "出库信息";
            if (stockType == 0)
            {
                fileName = "入库信息";
            }
            return File(buffer, ContentType.ContentTypeFile, DateTimeExt.GetDateTimeS(DateTimeExt.DateTimeFormatString) + "-" + EncoderUtil.UrlHttpUtilityEncoder(fileName) + ".xlsx");
        }


        #region 上传单个文件
        [HttpGet]
        public IActionResult Import(string date, string stockType)
        {
            ViewBag.date = date;
            ViewBag.stockType = stockType;

            return View();
        }


        [HttpPost]
        public IActionResult ImportExcelIn(IFormFile file)
        {
            string webRootPath = this._hostingEnvironment.WebRootPath;
            string fileExt = Path.GetExtension(file.FileName).ToLower();
            var filepath = Path.Combine(webRootPath, "excel", PubId.GetUuid()) + fileExt;

            return DelegateUtil.TryExecute<IActionResult>(() =>
            {
                using (var st = new MemoryStream())
                {
                    file.CopyTo(st);
                    var dt = NpoiUtil.Import(st, fileExt);
                    var json = this._stockinServices.Import(dt, UserDtoCache.UserId);
                    return Content(json.Item1 ? "1" : "0");
                }
            }, BootJsonH((false, PubConst.File3))
             );
        }

        [HttpPost]
        public IActionResult ImportExcelOut(IFormFile file)
        {
            string webRootPath = this._hostingEnvironment.WebRootPath;
            string fileExt = Path.GetExtension(file.FileName).ToLower();
            var filepath = Path.Combine(webRootPath, "excel", PubId.GetUuid()) + fileExt;

            return DelegateUtil.TryExecute<IActionResult>(() =>
            {
                using (var st = new MemoryStream())
                {
                    file.CopyTo(st);
                    var dt = NpoiUtil.Import(st, fileExt);
                    var json = this._stockinServices.Import(dt, UserDtoCache.UserId, 1);
                    return Content(json.Item1 ? "1" : "0");
                }
            }, BootJsonH((false, PubConst.File3))
             );
        }
        #endregion
    }
}